<?php

namespace app\http\middleware;

use app\constant\TenantConst;
use app\helper\TenantHelper;
use app\libs\Utils;
use app\model\AdminTenant;
use app\util\ReturnCode;

class AppTenantCheck
{

    /**
     * token鉴权
     * @param \think\facade\Request $request
     * @param \Closure $next
     * @return mixed|\think\response\Json
     */
    public function handle($request, \Closure $next)
    {
        //这里是方便后台管理编辑的时候需要调用手机端接口，作一个排除
        $ApiAuth = $request->header('appAuth', '');
        if ($ApiAuth) {
            $userInfo = cache('Login:' . $ApiAuth);
            $userInfo = json_decode($userInfo, true);
            $tid = $userInfo['tid'];
            $request->TID = $tid;
            return $next($request);
        }
        $host = $_SERVER['HTTP_TENANTHOST'];
        if (Utils::isEmpty($host)) {
            return json([
                'code' => ReturnCode::HOST_ERROR,
                'msg' => '非法域名',
                'data' => []
            ]);
        } else {
            $tid = TenantHelper::getHostCacheTid($host);
            if (!Utils::isEmpty($tid)) {
                $request->TID = $tid;
                return $next($request);
            } else {
                return json([
                    'code' => ReturnCode::HOST_ERROR,
                    'msg' => '无效的域名',
                    'data' => []
                ]);
            }
        }
    }
}
